package com.ljkj.blockpay.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.bumptech.glide.Glide;
import com.kongzue.baseokhttp.util.JsonList;
import com.kongzue.baseokhttp.util.JsonMap;
import com.ljkj.blockpay.R;
import com.ljkj.blockpay.basedata.BaseActivity;
import com.ljkj.blockpay.basedata.BasePresenterImpl;
import com.ljkj.blockpay.databinding.ActivityCashBinding;
import com.ljkj.blockpay.model.RechargeModel;
import com.ljkj.blockpay.presenter.RechargePresenter;
import com.ljkj.blockpay.presenter.inter.RechargeInter;
import com.ljkj.blockpay.ui.adapter.RechargeAdapter;
import com.ljkj.blockpay.util.ToggleToActivity;
import com.ljkj.blockpay.widget.ClickListener;
import com.ljkj.blockpay.widget.CommonDialog;
import com.luck.picture.lib.tools.ToastUtils;
import com.tbruyelle.rxpermissions3.Permission;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.yxing.ScanCodeConfig;
import com.yxing.def.ScanMode;
import com.yxing.def.ScanStyle;

import java.math.BigDecimal;
import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 提现页面
 */
public class CashActivity extends BaseActivity<ActivityCashBinding, RechargePresenter> implements RechargeInter.RechargeInterView,ClickListener {


    private CommonDialog withDrawDialog;
    private CommonDialog passwordDialog;
    private CommonDialog dismissDialog;
    private CommonDialog selectNetDialog;
    private String orderId;
    private RecyclerView currencylist;
    private CommonDialog mSelectdialog;
    private RechargeAdapter mRechargeAdapter;
    private String currencyName;
    private String currencyImg;
    private String origin;
    private BigDecimal originNumber;
    private String address;
    private String orderIds;
    private String targetAmount;
    private String networkType;
    private String targetAddress;
    private String originServiceAmount;
    private List<RechargeModel.NetworkDTO> modelList;
    private String networkTypes;
    private String balance;
    @Override
    public int initContentView() {
        return R.layout.activity_cash;
    }

    @Override
    protected RechargePresenter createPresenter() {

        return new RechargePresenter(this,this);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setOnClick(this::onClick);
        binding.topTitle.setTitleContent(R.string.withdraw);
        binding.topTitle.setLeftBackFinish(this);
    }

    @Override
    protected void initData() {
        super.initData();
        getPresenter().getNetAccuracy(3);
        mSelectdialog = CommonDialog.Builder.with(this).setContentView(R.layout.select_net)
                .setOnClickListener(R.id.tv_close, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mSelectdialog.dismiss();
                    }
                }).setCancelable(true).fullWidth().formBottom(true).create();
        GridLayoutManager lManager = new GridLayoutManager(this, 2);
        currencylist = mSelectdialog.findViewById(R.id.rv_currency);
        currencylist.setLayoutManager(lManager);
        mRechargeAdapter = new RechargeAdapter(R.layout.currnet_layout);
        currencylist.setAdapter(mRechargeAdapter);

        mRechargeAdapter.setOnItemClickListener((adapter, view, position) -> {
            modelList = mRechargeAdapter.getData();
            networkTypes = modelList.get(position).getNetworkType();

            binding.tvNets.setText(networkTypes);
            mSelectdialog.dismiss();
        });

        binding.etMinimumQuantity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (delayRun != null){
                    handler.removeCallbacks(delayRun);
                }
                handler.postDelayed(delayRun,1500);
            }
        });
    }

    private Handler handler = new Handler();
    private Runnable delayRun = new Runnable() {
        @Override
        public void run() {
            origin = binding.etMinimumQuantity.getText().toString();
            if (!origin.isEmpty()){
                binding.btnNext.setBackground(getResources().getDrawable(R.drawable.btnbg));
                originNumber = new BigDecimal(origin);
                getPresenter().preConfirm("",originNumber,3,networkTypes,binding.etAddress.getText().toString(),currencyName,"","");
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_none:
                ToggleToActivity.toSelectCurrencyActivity(this,10);
                break;
            case R.id.rl_netselect:
                mSelectdialog.show();
                break;
            case R.id.iv_selecticon:
                new RxPermissions(this)
                        .requestEachCombined(Manifest.permission.CAMERA)
                        .subscribe(new Observer<Permission>() {
                            @Override
                            public void onSubscribe(@NonNull Disposable d) {
                            }
                            @Override
                            public void onNext(@NonNull Permission permission) {
                                if (permission.granted) {
                                    ScanCodeConfig.create(CashActivity.this)
                                            .setStyle(ScanStyle.CUSTOMIZE)
                                            .setLimitRect(true)
                                            .setScanSize(800, 0, -200)
                                            .setShowFrame(true)
                                            .setFrameColor(R.color.blue_save)
                                            .setFrameRaduis(2)
                                            .setFrameWith(4)
                                            .setFrameLenth(15)
                                            .setShowShadow(true)
                                            .setShaowColor(R.color.black_tran30)
                                            .setScanMode(ScanMode.REVERSE)
                                            .setScanDuration(3000)
                                            .setScanBitmapId(R.mipmap.scan_line)
                                            .buidler()
                                            .start(ScanActivity.class);
                                }
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });
                break;


            case R.id.btn_next:
                String have = binding.tvUse.getText().toString();
                BigDecimal havebigDecimal = new BigDecimal(have);
                String inputnumber = binding.etMinimumQuantity.getText().toString();
                BigDecimal inputDecimal = new BigDecimal(inputnumber);
                if (binding.etAddress.getText().toString().isEmpty()){
                    ToastUtils.s(CashActivity.this,"提币地址不能为空");
                } else if (binding.etMinimumQuantity.getText().toString().isEmpty()){
                    ToastUtils.s(CashActivity.this,"提币数量不能为空");
                } else if (inputDecimal.compareTo(havebigDecimal) == 1){
                    ToastUtils.s(this,"提币数量大于所拥有的额度");
                }
                else {
                    binding.btnNext.setSelected(true);
                    if (origin != null){
                        originNumber = new BigDecimal(origin);
                        withDrawDialog = CommonDialog.Builder.with(this).setContentView(R.layout.withdraw_layout)
                                .forGravity(Gravity.BOTTOM)
                                .setOnClickListener(R.id.btn_ok, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        passwordDialog = CommonDialog.Builder.with(CashActivity.this)
                                                .setContentView(R.layout.codeedit_layout).forGravity(Gravity.BOTTOM).setOnClickListener(R.id.iv_close, new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View view) {

                                                        dismissDialog = CommonDialog.Builder.with(CashActivity.this).setContentView(R.layout.dropbusiness_layout)
                                                                .forGravity(Gravity.CENTER)
                                                                .setText(R.id.btn_ok,R.string.continuetrade)
                                                                .setOnClickListener(R.id.btn_cancel, new View.OnClickListener() {
                                                                    @Override
                                                                    public void onClick(View view) {
                                                                        ToggleToActivity.toMainActivity(CashActivity.this);
                                                                    }
                                                                })
                                                                .setOnClickListener(R.id.btn_ok, new View.OnClickListener() {
                                                                    @Override
                                                                    public void onClick(View view) {
                                                                        dismissDialog.dismiss();
                                                                    }
                                                                }).setCancelable(false).setOnKeyListener((dialog, keyCode, event) -> false).create();
                                                        dismissDialog.show();
                                                    }
                                                })
                                                .setOnClickListener(R.id.btn_ok, new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View view) {
                                                        getPresenter().createOrder(3,getPresenter().preOrderId,"123456");
                                                    }
                                                }).setCancelable(true).fullWidth().setOnKeyListener((dialog, keyCode, event) -> false).create();

                                        passwordDialog.show();
                                    }
                                })
                                .setOnClickListener(R.id.iv_close, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        withDrawDialog.dismiss();
                                    }
                                })
                                .fullWidth().setCancelable(true).setOnKeyListener((dialog, keyCode, event) -> false).create();
                        getPresenter().preConfirm("",originNumber,3,networkTypes,binding.etAddress.getText().toString(),currencyName,"","");
                        TextView withaccnumber = withDrawDialog.findViewById(R.id.tv_accountnumber);
                        TextView withcharge = withDrawDialog.findViewById(R.id.tv_charge);
                        TextView withnetkind = withDrawDialog.findViewById(R.id.tv_netkind);
                        TextView withaddress = withDrawDialog.findViewById(R.id.tv_address);
                        TextView withnumber = withDrawDialog.findViewById(R.id.tv_number);

                        withaccnumber.setText(targetAmount+" "+currencyName);
                        withcharge.setText(originServiceAmount);
                        withnetkind.setText(networkType);
                        withaddress.setText(binding.etAddress.getText().toString());
                        withnumber.setText(binding.etMinimumQuantity.getText().toString()+" "+currencyName);
                        withDrawDialog.show();
                    } else {
                        ToastUtils.s(this,"请填写金额");
                    }
                }
                break;
        }
    }

    @Override
    public void showNetAccuracy(List<RechargeModel> modelList) {
        if (modelList.size() != 0){
            mRechargeAdapter.setNewInstance(modelList.get(0).getNetwork());
            currencyName = modelList.get(0).getCurrencyName();
            currencyImg = modelList.get(0).getCurrencyImg();
            binding.tvCurrency.setText(currencyName);
            binding.tvUnit.setText(currencyName);
            if (originServiceAmount != null){
                binding.tvNumber.setText(originServiceAmount+""+currencyName);
            } else {
                binding.tvNumber.setText("0.00"+currencyName);
            }
            if (targetAmount != null){
                binding.tvAccountnumber.setText(targetAmount+" "+currencyName);
            } else {
                binding.tvAccountnumber.setText("0.00"+currencyName);
            }


            Glide.with(baseContext).load(currencyImg).into(binding.ivIcon);
            getPresenter().SearchCurrencyBalance(modelList.get(0).getCurrencyType(),3);
        }
    }

    @Override
    public void showrecharge(JsonMap jsonMap) {

    }


    @Override
    public void createOrderSuccess() {

    }

    @Override
    public void SearchCurrencySuccess(JsonMap jsondata) {
        balance = jsondata.getString("balance");
        binding.tvUse.setText(balance);
        binding.tvUseunit.setText(currencyName);
    }


    @Override
    public void getOrderDetails(JsonMap jsonMap) {
        getPresenter().preOrderId = jsonMap.getString("preOrderId");
        orderId = jsonMap.getString("orderId");
        originServiceAmount = jsonMap.getString("originServiceAmount");
        targetAmount = jsonMap.getString("targetAmount");
        networkType = jsonMap.getString("networkType");
        targetAddress = jsonMap.getString("targetAddress");
        binding.tvNumber.setText(originServiceAmount+""+currencyName);
        binding.tvAccountnumber.setText(targetAmount+" "+currencyName);


    }

    @Override
    public void getOrderDetails2(JsonMap jsonMap) {
        String orderIds = jsonMap.getString("orderId");
        ToggleToActivity.toTradingParticularActivity(CashActivity.this,3,orderIds);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //接收扫码结果
        if(resultCode == RESULT_OK && requestCode == ScanCodeConfig.QUESTCODE && data != null){
            Bundle extras = data.getExtras();
            if(extras != null){
                String code = extras.getString(ScanCodeConfig.CODE_KEY);
//                tvCode.setText(String.format("%s%s", "结果： " , code));
                ToastUtils.s(this,code);
            }
        }
        if (resultCode != 100) {
            return;
        }
        if (data.getExtras() != null) {
            Bundle bundle = data.getExtras();
            JsonMap jsonMap = JsonMap.parse(bundle.getString("jsonMap"));
            switch (requestCode) {
                case 10:
                    currencyName = jsonMap.getString("currencyName");
                    currencyImg = jsonMap.getString("currencyImg");
                    binding.tvCurrency.setText(currencyName);
                    Glide.with(baseContext).load(currencyImg).into(binding.ivIcon);
                    getPresenter().SearchCurrencyBalance(currencyName,3);
                    binding.tvUnit.setText(currencyName);
                    if (originServiceAmount != null){
                        binding.tvNumber.setText(originServiceAmount+""+currencyName);
                    } else {
                        binding.tvNumber.setText("0.00"+currencyName);
                    }

                    if (targetAmount != null){
                        binding.tvAccountnumber.setText(targetAmount+" "+currencyName);
                    } else {
                        binding.tvAccountnumber.setText("0.00"+currencyName);
                    }

                    break;
                default:
                    break;
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}